<?php

class Db {
	private $conn;
	private $db_prefix = '';
	private $rs;


	function __construct($hostname, $username, $password, $schema, $db_prefix = '') {
		$this->conn = mysql_connect($hostname, $username, $password);
		mysql_select_db($schema, $this->conn);
		$this->db_prefix = $db_prefix;
		$GLOBALS['db'] = $this;
	}


	function parse_query() {
		$args =& func_get_args();
		for ($i = 1, $max = count($args); $i < $max; ++$i)
			$args[$i] = addslashes($args[$i]);
		$args[0] = preg_replace("/{([^{} ]+)}/", $this->db_prefix . '\1', $args[0]);
		$query = call_user_func_array('sprintf', $args);
		if ($query === FALSE) {
			echo "sprintf() error!\n";
		}
		return $query;
	}


	function query() {
		if (!is_resource($this->conn)) {
			echo "Database not connected!\n";
			die;
		}
		$query = call_user_func_array(array($this, 'parse_query'), func_get_args());
		//echo "QUERY: " . addcslashes(preg_replace("/^[ \t]+/m", '', $query), "\x00..\x09\x0B..\x1F") . "\n\n";
		$this->rs = mysql_query($query, $this->conn);
		if ($this->rs === FALSE) {
			echo "\nDB_ERROR:\n" . $this->error() . "\n";
		}
		return $this->rs;
	}


	function result($rs) {
		if ($rs && mysql_num_rows($rs) > 0) {
			$row = $this->fetch_row($rs);
			return $row[0];
		}
		return FALSE;
	}


	function fetch_array($rs = NULL) {
		$obj = mysql_fetch_object($rs ? $rs : $this->rs);
		if (!$obj) return FALSE;
		return (array)$obj;
	}

	function fetch_row($rs = NULL) { return mysql_fetch_row($rs ? $rs : $this->rs); }

	function fetch_object($rs = NULL) { return mysql_fetch_object($rs ? $rs : $this->rs); }

	function affected_rows() { return mysql_affected_rows($this->conn); }

	function last_insert_id($table, $field) { return $this->result($this->query('SELECT LAST_INSERT_ID()')); }

	function error() { return mysql_error($this->conn); }

}




